package mongo

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/tools"
	"io/ioutil"
	"os"
	"path"
	"runtime"
	"strings"
)

func (doc *Document) CreateVueAdminFile() {
	var root string
	_, filename, _, ok := runtime.Caller(0)
	if ok {
		root = path.Dir(filename)
	}
	//path := root + "/tpl/vue/admin"
	path := root + "/tpl/vue/quasar"
	target := "./output/"
	err := tools.CreateDirForPath("./output/1.txt")
	_, err = os.Stat("./output")
	if os.IsNotExist(err) {
		os.Mkdir("./output", 0777)
	}
	if err != nil {
		println(err.Error())
	}
	files, err := ioutil.ReadDir(path)
	if err != nil {
		println(err.Error())
	}
	for _, file := range files {
		if file.Name() == "js" {
			continue
		}
		content, _ := ioutil.ReadFile(path + "/" + file.Name())
		tpl := string(content)
		tpl = strings.ReplaceAll(tpl, "__DIR__", doc.Path)
		tpl = strings.ReplaceAll(tpl, "__EN_NAME__", doc.Name)
		tpl = strings.ReplaceAll(tpl, "__CN_NAME__", doc.CnName)
		//默认配置信息输入
		e := tools.CreateDirForPath(target + doc.Path + "/" + doc.Name + "/" + file.Name())
		if e != nil {
			println(e.Error())
		}
		err = ioutil.WriteFile(target+doc.Path+"/"+doc.Name+"/"+file.Name(), []byte(tpl), 0777)
		if err != nil {
			println(err.Error())
		}
	}
	//path = root + "/tpl/vue/admin/js"
	path = root + "/tpl/vue/quasar/js"
	files, err = ioutil.ReadDir(path)
	if err != nil {
		println(err.Error())
	}

	//D单独处理字段的那些信息
	//lb.add("id","#",80)
	//fb.addText("name","姓名",3)
	formRows := ""
	listRows := ""
	for _, field := range doc.Fields {
		fName := strings.ToLower(field.Name[0:1]) + field.Name[1:]
		formRows += fmt.Sprintf(`fb.addText("%s","%s",6)`, fName, field.CnName) + "\n"
		listRows += fmt.Sprintf(`lb.add("%s","%s",100)`, fName, field.CnName) + "\n"
	}

	for _, file := range files {
		content, _ := ioutil.ReadFile(path + "/" + file.Name())
		tpl := string(content)
		tpl = strings.ReplaceAll(tpl, "__DIR__", doc.Path)
		tpl = strings.ReplaceAll(tpl, "__EN_NAME__", doc.Name)
		tpl = strings.ReplaceAll(tpl, "__CN_NAME__", doc.CnName)
		tpl = strings.ReplaceAll(tpl, "__FORM_BUILDER__", formRows)
		tpl = strings.ReplaceAll(tpl, "__LIST_BUILDER__", listRows)
		//默认配置信息输入
		tools.CreateDirForPath(target + doc.Path + "/" + doc.Name + "/js/" + file.Name())
		err = ioutil.WriteFile(target+doc.Path+"/"+doc.Name+"/js/"+file.Name(), []byte(tpl), 0777)
		if err != nil {
			println(err.Error())
		}
	}
	//jsApi特殊文件
	content := `import api from "./api"
export default {
    ...api
}`
	os.WriteFile(target+doc.Path+"/"+doc.Name+"/js/api"+doc.Name+".js", []byte(content), 0777)

	rContent, _ := os.ReadFile(target + doc.Path + "/" + doc.Name + "/js/_r.js")
	os.WriteFile(target+doc.Path+"/"+doc.Name+"/js/_r"+doc.Name+".js", rContent, 0777)
	//删除_r文件
	os.Remove(target + doc.Path + "/" + doc.Name + "/js/_r.js")

	println("后台代码生成成功", doc.CnName, doc.Name)
}
